//
//  YDDatabase.swift
//  YDPerfectServer
//
//  Created by rowena on 2019/8/2.
//
//
// 开启数据库 需要在命令行中允许 mysql.server start

import PerfectMySQL

let YDDatabaseHost = "localhost"
let YDDatabaseUser = "mysql"
let YDDatabasePassword = "WyZgh123.654"
let YDDatabaseName = "YDDatabase"
let YDDatabasePort: Int32 = 22
let YDDatabaseSocket = "39.97.250.51"

//let YDDatabaseHost = "localhost"
//let YDDatabaseUser = "root"
//let YDDatabasePassword = "WyZgh123.654"
//let YDDatabaseName = "YDDatabase"
//let YDDatabasePort: Int32 = 3306
//let YDDatabaseSocket = "10.0.2.21"

class YDDatabase {

    /** 创建本地数据库 */
    let mysql = MySQL()
    
    init() {
        self.connectDatabase()
    }
    
    /**
     * 链接本地数据库
     */
    func connectDatabase() {
        let connected = mysql.connect(host: YDDatabaseHost, user: YDDatabaseUser, password: YDDatabasePassword, db: YDDatabaseName)
        guard connected else {
            //链接数据库，不带数据库名称
            let connect = mysql.connect(host: YDDatabaseHost, user: YDDatabaseUser, password: YDDatabasePassword)
            guard connect else {  return }
            //创建数据库
            if self.createDatabase(databaseName: YDDatabaseName) {
                //重新链接数据库，带数据库名称
                guard mysql.connect(host: YDDatabaseHost, user: YDDatabaseUser, password: YDDatabasePassword, db: YDDatabaseName) else {  return }
            }
            return
        }
    }
    
    /**
     * 创建本地数据库
     * @pram databaseName 将要创建数据库名称
     * @return 返回创建数据库结果 true：成功 false：失败
     */
    func createDatabase(databaseName: String) -> Bool {
        let statement: String = "create database " + databaseName
        
        return mysql.query(statement: statement)
    }
    
    /**
     * 删除数据库中已存在的表
     * @pram tableName 将要删除表的名字
     * @return 返回表是否删除成功 true：成功 false：失败
     */
    func deleteTable(tableName: String) -> Bool {
        let statement: String = "DROP TABLE IF EXISTS " + tableName
        
        return mysql.query(statement: statement)
    }
}
